package com.lenovo.smarttraffic.zm;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.google.gson.Gson;
import com.lenovo.smarttraffic.Constant;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.Test.User;
import com.lenovo.smarttraffic.api.ParkingApi;
import com.lenovo.smarttraffic.ui.activity.BaseActivity;
import com.lenovo.smarttraffic.ui.fragment.fgBean.JsonBean;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class StopCarActivity extends BaseActivity implements Serializable {
    String TAG = "wwwwwwwwwwwwwwwwwww";
    AMap aMap = null;
    MapView mMapView = null;
    private ImageView ivMapLocation;
    private ImageView ivMapMarket;
    private ImageView ivMapPlayer;
    private ImageView ivMapLine;
    private ListView lvStopCar;
    public static int anpostion;
    private CarParkInfo carParkInfo;
    private String url = "http://192.168.1.110:8088/transportservice/action/GetCarParkInfo.do";
    private Marker marker;
    List<BitmapDescriptor> listbitmap = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.map);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);
        //定义了一个地图view
        // 此方法须覆写，虚拟机需要在很多情况下保存地图绘制的当前状态。
        //初始化地图控制器对象
        if (aMap == null) {
            aMap = mMapView.getMap();
            aMap.setLoadOfflineData(true);
            aMap.reloadMap();
        }
        initView();
    }


    private void initView() {
        BitmapDescriptor bitmap0 = BitmapDescriptorFactory.fromResource(R.mipmap.marker_one);
        BitmapDescriptor bitmap1 = BitmapDescriptorFactory.fromResource(R.mipmap.marker_second);
        BitmapDescriptor bitmap2 = BitmapDescriptorFactory.fromResource(R.mipmap.marker_thrid);
        BitmapDescriptor bitmap3 = BitmapDescriptorFactory.fromResource(R.mipmap.marker_forth);
        listbitmap.add(bitmap0);
        listbitmap.add(bitmap1);
        listbitmap.add(bitmap2);
        listbitmap.add(bitmap3);
        initToolBar(findViewById(R.id.toolbar), true, "停车场");
        lvStopCar = (ListView) findViewById(R.id.lv);
        ivMapLocation = (ImageView) findViewById(R.id.ivMapLocation);
        ivMapPlayer = (ImageView) findViewById(R.id.ivMapPlayer);
        ivMapLine = (ImageView) findViewById(R.id.ivMapLine);
        ivMapMarket = (ImageView) findViewById(R.id.ivMapMarket);

        http();

        ivMapLocation.setOnClickListener((view) -> {
            LatLng latLng = new LatLng(39.941853, 116.385307);//经纬度设置
            changeCamera(
                    //将地图移动到定位点   设置缩放
                    //newCameraPosition 给地图设置一个新的状态
                    CameraUpdateFactory.newCameraPosition(
                            //CameraPosition(
                            // 经纬度,目标可视区域的缩放级别,
                            // 目标可视区域的倾斜度，
                            // 以角度为单位,可视区域指向的方向，
                            // 以角度为单位，从正北向顺时针方向计算，从0度到360度)
                            new CameraPosition(latLng, 15, 0, 30)), null);


            //设置定位点的marker
            marker = aMap.addMarker(new MarkerOptions().position(latLng).title("什刹海"));
            //在定位图钉中加入图片
            BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.marker_self);
            marker.setIcon(bitmap);
        });
        //让listView  重新隐藏
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                lvStopCar.setVisibility(View.INVISIBLE);
            }
        });

    }

    private void changeCamera(CameraUpdate update, AMap.CancelableCallback callback) {
        aMap.animateCamera(update, 500, callback);
    }


//    private void okhttp() {
//        JSONObject jsonObject = new JSONObject();
//        try {
//            jsonObject.put("UserName", "user1");
//            OkHttpUtils1.doRequest(url, jsonObject.toString(), new OkHttpUtils1.OnResLis() {
//                @Override
//                public void success(String resutl) {
//                    Gson gson = new Gson();
//                    carParkInfo = gson.fromJson(resutl, CarParkInfo.class);
//                    initCoordinate();
//                    sortCarPark();
//
//                    StopCarAdapter adapter = new StopCarAdapter();
//
//                    ivMapMarket.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View view) {
//                            showMarket();
//                            lvStopCar.setAdapter(adapter);
//                            adapter.notifyDataSetChanged();
//                            lvStopCar.setVisibility(View.VISIBLE);
//                        }
//                    });
//                }
//            });
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    private void http() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.1.110:8088/transportservice/action/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        ParkingApi parkingApi = retrofit.create(ParkingApi.class);
        Call<CarParkInfo> call = parkingApi.getCall(new JsonBean("user1"));
        call.enqueue(new Callback<CarParkInfo>() {
            @Override
            public void onResponse(Call<CarParkInfo> call, Response<CarParkInfo> response) {
                carParkInfo = response.body();
                initCoordinate();
                sortCarPark();
                StopCarAdapter adapter = new StopCarAdapter();
                ivMapMarket.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        showMarket();
                        lvStopCar.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
                        lvStopCar.setVisibility(View.VISIBLE);
                    }
                });
            }

            @Override
            public void onFailure(Call<CarParkInfo> call, Throwable t) {

            }
        });

    }

    //按距离排序
    private void sortCarPark() {
        //未排序  只是用来计算distance 方便下一步排序
        String coordinate0 = carParkInfo.getROWS_DETAIL().get(0).getCoordinate();
        String coordinate1 = carParkInfo.getROWS_DETAIL().get(1).getCoordinate();
        String coordinate2 = carParkInfo.getROWS_DETAIL().get(2).getCoordinate();
        String coordinate3 = carParkInfo.getROWS_DETAIL().get(3).getCoordinate();
        Marker marker = MarkerAdd(coordinate0, 0);
        Marker marker1 = MarkerAdd(coordinate1, 1);
        Marker marker2 = MarkerAdd(coordinate2, 2);
        Marker marker3 = MarkerAdd(coordinate3, 3);


        //集合里面是一个类    可以用这种方法排序
        Collections.sort(carParkInfo.getROWS_DETAIL(), new Comparator<CarParkInfo.ROWSDETAILBean>() {
            @Override
            public int compare(CarParkInfo.ROWSDETAILBean t0, CarParkInfo.ROWSDETAILBean t1) {
                return (int) (t0.getDistance() - t1.getDistance());
            }
        });


    }

    private void showMarket() {
        //已排序  重新定义markerView 图片顺序
        //并显示marker
        String coordinate00 = carParkInfo.getROWS_DETAIL().get(0).getCoordinate();
        String coordinate01 = carParkInfo.getROWS_DETAIL().get(1).getCoordinate();
        String coordinate02 = carParkInfo.getROWS_DETAIL().get(2).getCoordinate();
        String coordinate03 = carParkInfo.getROWS_DETAIL().get(3).getCoordinate();
        Marker marker00 = MarkerAdd(coordinate00, 0);
        Marker marker01 = MarkerAdd(coordinate01, 1);
        Marker marker02 = MarkerAdd(coordinate02, 2);
        Marker marker03 = MarkerAdd(coordinate03, 3);
        marker00.setVisible(true);
        marker01.setVisible(true);
        marker02.setVisible(true);
        marker03.setVisible(true);
    }

    private Marker MarkerAdd(String s, int w) {


        Double[] a = new Double[2];
        String result[] = s.split(",");
        for (int i = 0; i < result.length; i++) {
            a[i] = Double.valueOf(result[i]);
        }
        LatLng latLng = new LatLng(a[0], a[1]);
        Marker makerA = aMap.addMarker(new MarkerOptions().position(latLng)
                .draggable(false)
                .icon(listbitmap.get(w)));
        makerA.setVisible(false);
        LatLng defaultLatLng = new LatLng(39.941853, 116.385307);
        //计算距离
        float distance = AMapUtils.calculateLineDistance(makerA.getPosition(), defaultLatLng);
        carParkInfo.getROWS_DETAIL().get(w).setDistance(distance);


        return makerA;
    }


    public class StopCarAdapter extends BaseAdapter {

        private LinearLayout llItem;
        private TextView tvSerial;
        private TextView tvStopInfo;
        private TextView tvEmpty;
        private ImageView ivEnter;

        @Override
        public int getCount() {
            return carParkInfo.getROWS_DETAIL().size();
        }

        @Override
        public Object getItem(int position) {
            return carParkInfo.getROWS_DETAIL().get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = LayoutInflater.from(StopCarActivity.this).inflate(R.layout.item_stop, parent, false);
            llItem = (LinearLayout) view.findViewById(R.id.ll_item);
            tvSerial = (TextView) view.findViewById(R.id.tv_serial);
            tvStopInfo = (TextView) view.findViewById(R.id.tv_stop_info);
            tvEmpty = (TextView) view.findViewById(R.id.tv_empty);
            ivEnter = (ImageView) view.findViewById(R.id.iv_enter);
            tvSerial.setText(position + 1 + "");

            tvStopInfo.setText(carParkInfo.getROWS_DETAIL().get(position).getName() + "\n空车位" + carParkInfo.getROWS_DETAIL().get(position).getEmptyspace() + ","
                    + carParkInfo.getROWS_DETAIL().get(position).getRemarks() + "\n" + carParkInfo.getROWS_DETAIL().get(position).getAddress() + "  " + (int) carParkInfo.getROWS_DETAIL().get(position).getDistance() + "m");
            //先判断开不开放在判断满不满

            if (carParkInfo.getROWS_DETAIL().get(position).getOpen() == 1) {//等于1就是开放
                if (carParkInfo.getROWS_DETAIL().get(position).getEmptyspace() == 0) {//等于0就是车位已满
                    tvEmpty.setVisibility(View.VISIBLE);
                    tvEmpty.setText("已满");
                    tvEmpty.setTextColor(Color.parseColor("#FF8F7425"));
                    llItem.setBackgroundColor(Color.GRAY);
                } else {//不等于0就是还有车位
                    ivEnter.setVisibility(View.VISIBLE);
                    ivEnter.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(StopCarActivity.this, ParkActivity.class);
                            Bundle bundle = new Bundle();
                            CarParkInfo.ROWSDETAILBean bean = carParkInfo.getROWS_DETAIL().get(position);
                            bundle.putSerializable("bean", (Serializable) bean);
                            intent.putExtras(bundle);
                            startActivity(intent);

                        }
                    });
                }
            } else {//不等于1就是关闭
                tvEmpty.setVisibility(View.VISIBLE);
                tvEmpty.setText("关闭");
                tvEmpty.setTextColor(Color.parseColor("#FF8F7425"));
                llItem.setBackgroundColor(Color.GRAY);
            }

            return view;
        }
    }


    // api里没有经纬度   所以自己给赋值
    // 再去使用
    private void initCoordinate() {
        carParkInfo.getROWS_DETAIL().get(0).setCoordinate("39.940478,116.395028");
        carParkInfo.getROWS_DETAIL().get(1).setCoordinate("39.935137,116.379151");
        carParkInfo.getROWS_DETAIL().get(2).setCoordinate("39.945769,116.391412");
        carParkInfo.getROWS_DETAIL().get(3).setCoordinate("39.936864,116.38517");
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_stop_car;
    }

}
